<script setup>
import {
  createCategoryAPI,
  deleteCategoryAPI,
  getCategoryListAPI,
  updateCategoryAPI,
} from '@/api'
import errorLogger from '@/utils/errorLogger'
import { ref, onMounted } from 'vue'
import { Folder } from 'lucide-vue-next'
import { ElMessage } from 'element-plus'

// 列表数据与分页参数
const categoryList = ref([])
const pageParams = ref({ currentPage: 1, pageSize: 10 })
const totalCategories = ref(0)

// 获取分类列表：调用后端分页接口并更新本地数据
// 注释：这里使用 getCategoryListAPI 获取数据，成功后赋值给 categoryList 和 totalCategories
const fetchCategories = async () => {
  try {
    const res = await getCategoryListAPI(pageParams.value)
    // 假设接口返回 { data: { list: [], total: number } }
    categoryList.value = res.data.list || []
    totalCategories.value = res.data.total || 0
  } catch (err) {
    // 记录错误方便排查
    errorLogger(err)
  }
}

onMounted(() => {
  fetchCategories()
})

// 对话框相关状态（用于创建与更新同一弹窗）
const dialogVisible = ref(false)
const name = ref('')
const isEditing = ref(false)
const editingId = ref(null)

// 重置对话框状态
const resetDialog = () => {
  name.value = ''
  isEditing.value = false
  editingId.value = null
}

// 关闭对话框时重置并关闭
const handleClose = () => {
  resetDialog()
  dialogVisible.value = false
}

// 创建分类：调用 createCategoryAPI
// 注释：创建成功后重新拉取列表并显示成功提示
const handleCreateCategory = async () => {
  try {
    await createCategoryAPI({ name: name.value })
    await fetchCategories()
    ElMessage.success('分类创建成功')
  } catch (err) {
    errorLogger(err)
    throw err
  }
}

// 更新分类：调用 updateCategoryAPI
// 注释：更新成功后重新拉取列表并显示成功提示
const handleUpdateCategory = async () => {
  try {
    // 使用 editingId（可能为 id 或 _id），接口需要 id 字段
    const id = editingId.value
    await updateCategoryAPI({ id, name: name.value })
    await fetchCategories()
    ElMessage.success('分类更新成功')
  } catch (err) {
    errorLogger(err)
    throw err
  }
}

// 提交按钮的统一处理：根据 isEditing 决定是创建还是更新
const handleSubmit = async () => {
  try {
    if (isEditing.value) {
      await handleUpdateCategory()
    } else {
      await handleCreateCategory()
    }
    dialogVisible.value = false
    resetDialog()
  } catch {
    // 错误已在具体函数中记录
  }
}

// 打开创建对话框
const openCreateDialog = () => {
  resetDialog()
  isEditing.value = false
  dialogVisible.value = true
}

// 打开编辑对话框并预填数据
const openEditDialog = (category) => {
  isEditing.value = true
  // 后端可能返回 id 或 _id，优先使用 id，否则使用 _id
  editingId.value = category.id || category._id || null
  name.value = category.name || ''
  dialogVisible.value = true
}

// 删除相关：使用 popover 做二次确认
const activePopoverId = ref(null)
const showPopover = (id) => (activePopoverId.value = id)
const hidePopover = () => (activePopoverId.value = null)

// 删除分类：调用 deleteCategoryAPI
// 注释：删除成功后重新拉取列表并关闭确认弹窗
const handleDeleteCategory = async (id) => {
  try {
    await deleteCategoryAPI(id)
    await fetchCategories()
    hidePopover()
    ElMessage.success('分类删除成功')
  } catch (err) {
    errorLogger(err)
  }
}
</script>

<template>
  <el-card>
    <template #header>
      <div>
        <el-text size="large">分类管理</el-text>
        <el-button
          type="primary"
          @click="openCreateDialog"
          style="float: right">
          创建分类
        </el-button>
      </div>
    </template>

    <div class="card-container">
      <el-card
        v-for="category in categoryList"
        :key="category.id || category._id"
        shadow="hover">
        <div class="top">
          <Folder :size="20" />
          <p>{{ category.name }}</p>
        </div>
        <div class="bottom">
          <div>
            <el-button
              size="small"
              type="primary"
              @click="openEditDialog(category)"
              >编辑</el-button
            >

            <el-popover
              :visible="activePopoverId === (category.id || category._id)"
              placement="top"
              :width="220">
              <p>确定要删除此分类吗？</p>
              <div style="text-align: right; margin: 0">
                <el-button size="small" text @click="hidePopover"
                  >取消</el-button
                >
                <el-button
                  size="small"
                  type="primary"
                  @click="handleDeleteCategory(category.id || category._id)"
                  >确认</el-button
                >
              </div>
              <template #reference>
                <el-button
                  size="small"
                  type="danger"
                  @click="showPopover(category.id || category._id)"
                  >删除</el-button
                >
              </template>
            </el-popover>
          </div>
        </div>
      </el-card>
    </div>

    <div class="pagination">
      <el-pagination
        v-model:current-page="pageParams.currentPage"
        v-model:page-size="pageParams.pageSize"
        layout="total, prev, pager, next"
        :total="totalCategories"
        @current-change="fetchCategories"
        background />
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="isEditing ? '编辑分类' : '创建分类'"
      width="500"
      :before-close="handleClose">
      <el-input v-model="name" placeholder="请输入分类名称" label="分类名称" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </el-card>
</template>

<style scoped lang="scss">
.card-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 20px;

  .top {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .bottom {
    margin-top: 20px;
  }
}

.pagination {
  margin-top: 24px;
  @include flex-center;
}
</style>
